/*
 * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License.
 */
package org.jflame.uid.worker;

import org.jflame.uid.IDGenerateException;
import org.jflame.uid.snowflake.utils.DockerUtils;
import org.jflame.uid.utils.NetUtils;
import org.jflame.uid.worker.dao.IWorkerNodeDao;
import org.jflame.uid.worker.entity.WorkerNodeEntity;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents an implementation of {@link WorkerIdAssigner}, the worker id will be discarded after assigned to the
 * UidGenerator
 * 
 * @author yutianbao
 */
public class DisposableWorkerIdAssigner implements WorkerIdAssigner {

    private static final Logger logger = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class);

    private IWorkerNodeDao workerNodeDAO;

    public DisposableWorkerIdAssigner(IWorkerNodeDao workerNodeDAO) {
        this.workerNodeDAO = workerNodeDAO;
    }

    /**
     * Assign worker id base on database.
     * <p>
     * If there is host name and port in the environment, we considered that the node runs in Docker container<br>
     * Otherwise, the node runs on an actual machine.
     * 
     * @return assigned worker id
     */
    public int assignWorkerId() {
        // build worker node entity
        WorkerNodeEntity workerNodeEntity = buildWorkerNode();

        // add worker node for new (ignore the same IP + PORT)
        boolean success = workerNodeDAO.registerWorkerNode(workerNodeEntity);
        if (success) {
            logger.info("Add worker node:" + workerNodeEntity);
            return workerNodeEntity.getId();
        } else {
            logger.error("注册workId失败:{}", workerNodeEntity);
            throw new IDGenerateException("注册workId失败");
        }
    }

    /**
     * Build worker node entity by IP and PORT
     */
    private WorkerNodeEntity buildWorkerNode() {
        WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
        if (DockerUtils.isDocker()) {
            workerNodeEntity.setNodeType(WorkerNodeType.CONTAINER.value());
            workerNodeEntity.setHostName(DockerUtils.getDockerHost());
            workerNodeEntity.setPort(DockerUtils.getDockerPort());
        } else {
            workerNodeEntity.setNodeType(WorkerNodeType.ACTUAL.value());
            workerNodeEntity.setHostName(NetUtils.getLocalAddress());
            workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(1, 100000));
        }

        return workerNodeEntity;
    }

}
